package com.jiu345.users.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jiu345.api.mapper.CartMapper;
import com.jiu345.api.mapper.GoodsMapper;
import com.jiu345.api.mapper.GoodsSkusMapper;
import com.jiu345.api.pojo.Goods;
import com.jiu345.api.pojo.GoodsSkus;
import com.jiu345.api.pojo.vo.CartVo;
import com.jiu345.core.page.PageQuery;
import com.jiu345.core.page.TableDataInfo;
import com.jiu345.users.mapper.AddressMapper;
import com.jiu345.users.mapper.OrderInfoMapper;
import com.jiu345.users.mapper.OrderMapper;
import com.jiu345.users.pojo.Address;
import com.jiu345.users.pojo.Order;
import com.jiu345.users.pojo.OrderInfo;
import com.jiu345.users.pojo.bo.CartBo;
import com.jiu345.users.pojo.bo.NowBuyBo;
import com.jiu345.users.pojo.bo.OrderBo;
import com.jiu345.users.pojo.vo.OrderVo;
import com.jiu345.users.pojo.vo.Summary;
import com.jiu345.users.service.IAddressService;
import com.jiu345.users.service.IOrderService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * @author MrLei QQ:235921049
 * desc:用户订单
 * @Date 2024.08.01 19:34
 */
@RequiredArgsConstructor
@Service
public class IOrderServiceImpl implements IOrderService {
    private final OrderMapper baseMapper;
    private final CartMapper cartMapper;
    private final AddressMapper addressMapper;
    private final GoodsSkusMapper skusMapper;
    private final GoodsMapper goodsMapper;
    private final OrderInfoMapper infoMapper;

    //查询当前登录用户
    private long getUserId() {
        return StpUtil.getLoginIdAsLong();
    }
    /*根据用户ID查询所有订单*/
    @Override
    public TableDataInfo<Order> queryPageList(Order bo, PageQuery pageQuery) {
        Page<Order> result = baseMapper.queryPageList(pageQuery.build(), bo);
        return TableDataInfo.build(result);
    }

    /*新增用户订单*/
    @Override
    public Order insertByBo(OrderBo bo) {
        // 1. 获取当前时间并转换成 'yyyymmddHHssmm' 格式
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String currentTime = sdf.format(new Date());

        // 2. 生成6位随机数
        Random random = new Random();
        int randomNumber = random.nextInt(900000) + 100000; // 生成100000到999999之间的随机数

        // 3. 将时间与6位随机数拼接后赋值给 bo.setOrderNo()
        String orderNo = currentTime + randomNumber;
        // 创建新对象并赋值
        Order order = new Order();
        //TODO卖家ID，要根据商品的卖家ID查询出来赋值，如果用户提交是多个卖家的商品，则要把单进行分割，按一个商家一个订单来生成
        //赋值
        order.setOrderNo(orderNo);
        order.setUserId(getUserId());
        order.setTenantId("000000");//TODO要生成动态
        order.setTotalPrice(bo.getTotalPrice());
        order.setTotalPayPrice(bo.getTotalPayPrice());
        order.setReceiveName(bo.getReceiveName());
        order.setReceiveTel(bo.getReceiveTel());
        order.setReceiveAddress(bo.getReceiveAddress());
        order.setReceiveArea(bo.getReceiveArea());

        order.setCreateTime(new Date());
        order.setUpdateTime(new Date());
        //4.保存order主表
        int flag = baseMapper.insert(order);
        if(flag > 0) {
            bo.getGoods().forEach(sku->{
                OrderInfo orderInfo = new OrderInfo();
                //遍历后给order_info赋值
                orderInfo.setOrderId(order.getId());
                orderInfo.setSkuId(sku.getId());
                orderInfo.setGoodsName(sku.getGoodsName());
                orderInfo.setSkuName(sku.getSkuName());
                orderInfo.setSkuImgUrl(sku.getSkuImgUrl());
                orderInfo.setCount(sku.getCount());
                orderInfo.setPrice(sku.getPrice());
                orderInfo.setTotalPrice(BigDecimal.valueOf(Long.parseLong(sku.getPrice().toString()) * Long.parseLong(sku.getCount().toString())));
                orderInfo.setCreateTime(new Date());
                orderInfo.setUpdateTime(new Date());
                //保存order_info表
                infoMapper.insert(orderInfo);

            });
        }
        // 保存前校验
        validEntityBeforeSave(bo);
        //TODO 提交成功后，要判断这个订单是从购物车还是立即购买，如果是购物车，则需要删除购物车里已购商品列表
        //1.遍历商品列表
        //2.查询购物车列表
        //3.如果购物车商品==列表商品并且数量也相等时，则清除购物车里的

        return order;
    }

    /*查询用户待提交订单的商品列表*/
    public OrderVo createByCart() {
        long userId = getUserId();
        //获取购物车中字段selected=true的商品列表
        List<CartVo> cartVos =cartMapper.selectCartDetailsByUserId(userId);
        // 获取购物车总数和总价
        Map<String, Object> summaryData = cartMapper.selectCartSummaryByUserId(userId);
        //类型转换
        Integer goodsCount = Integer.valueOf(summaryData.get("goodsCount").toString()) ;
        Double totalPrice = Double.valueOf(summaryData.get("totalPrice").toString()) ;
        OrderVo orderPre = new OrderVo();
        orderPre.setGoods(cartVos);
        //折扣
        Double discountPrice = Double.valueOf("5") ;
        //运费(根据商品是否包邮设置动态）
        Double postFee = Double.valueOf("8") ;
        //创建一个Summary对象
        Summary summary = new Summary();
        summary.setDiscountPrice(discountPrice);//折扣金额
        summary.setGoodsCount(goodsCount);//商品数量
        summary.setTotalPrice(totalPrice);//商品金额
        summary.setPostFee(postFee);//邮费
        summary.setTotalPayPrice(totalPrice + postFee - discountPrice);//应付金额（总价 + 邮费 - 折扣）
        orderPre.setSummary(summary);
        //查询用户收到货地址
        List<Address> addresses = getUserAddresses(userId);
        orderPre.setUserAddresses(addresses);
        //返回待创建订单列表
        return orderPre;
    }

    /*查询用户立即购买商品*/
    public OrderVo nowBuy(NowBuyBo bo) {
        long userId = getUserId();

        //查询SKU
        LambdaQueryWrapper<GoodsSkus> eq = new LambdaQueryWrapper<GoodsSkus>().eq(GoodsSkus::getId, bo.getSkuId());
        GoodsSkus sku = skusMapper.selectOne(eq);
        //查询sku的商品名称
        LambdaQueryWrapper<Goods> goodsLqw = new LambdaQueryWrapper<Goods>().eq(Goods::getId, sku.getGoodsId());
        Goods goods = goodsMapper.selectOne(goodsLqw);

        CartVo cartVo = CartVo.builder()
            .goodsName(goods.getName())
            .count(bo.getCount())
            .skuId(sku.getId())
            .skuName(sku.getSkuName())
            .skuImgUrl(sku.getImgUrl())
            .price(sku.getPrice())
            .build();

        CartVo[] goodsArray = new CartVo[]{cartVo};
        OrderVo orderPre = new OrderVo();
        //因为setGoods需要的是一个数组，所以需要将cartVo转换成数组
        orderPre.setGoods(List.of(goodsArray));

        //折扣
        double discountPrice = Double.parseDouble("5");
        //运费(根据商品是否包邮设置动态）
        Double postFee = Double.valueOf("8") ;
        //创建一个Summary对象
        Summary summary = new Summary();
        summary.setDiscountPrice(discountPrice);//折扣金额
        summary.setGoodsCount(bo.getCount());//商品数量

        Double totalPrice = Double.parseDouble(bo.getCount().toString()) * Double.parseDouble(sku.getPrice().toString());
        summary.setTotalPrice(totalPrice);//商品金额
        summary.setPostFee(postFee);//邮费
        summary.setTotalPayPrice(totalPrice + postFee - discountPrice);//应付金额（总价 + 邮费 - 折扣）


        orderPre.setSummary(summary);
        //查询用户收到货地址
        List<Address> addresses = getUserAddresses(userId);
        orderPre.setUserAddresses(addresses);
        //返回待创建订单列表
        return orderPre;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(OrderBo entity) {
        //TODO 做一些数据校验,如唯一约束
        //entity.setUpdateBy(SecurityUtils.getCurrentUserId());
    }

    /*查询用户收货地址*/
    private List<Address> getUserAddresses(Long userId) {
        return addressMapper.selectByUserIdAddresses(userId);
    }
    //TODO 提取订单摘要信息计算 -抽离共用部分
    private Summary calculateSummary(List<CartVo> cartVos, int count, double discountPrice, double postFee) {
        int goodsCount = cartVos != null ? cartVos.size() : count;
        double totalPrice = 0.0;
        if (cartVos != null) {
            for (CartVo cartVo : cartVos) {
                totalPrice += Long.parseLong(cartVo.getPrice().toString()) * cartVo.getCount();
            }
        } else {
            // 假设这里有一个单价和数量的参数
            // totalPrice = 单价 * 数量; 但因为nowBuy方法中已处理，这里仅作示意
        }
        Summary summary = new Summary();
        summary.setDiscountPrice(discountPrice);
        summary.setGoodsCount(goodsCount);
        summary.setTotalPrice(totalPrice);
        summary.setPostFee(postFee);
        summary.setTotalPayPrice(totalPrice + postFee - discountPrice);
        return summary;
    }
}
